﻿using IDataAccessLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
using System.Data.Entity;
using Z.EntityFramework.Plus;

namespace DataAccessLayer
{
    //不再设为抽象类 对一些只有简单访问的类不用重新写单独的Dal
    public class BaseDal<T> : IBaseDal<T> where T : class
    {
        protected MusicStoreContext baseContext;
        protected IDbSet<T> objectSet;

        public BaseDal()
        {
            baseContext = new MusicStoreContext();
            objectSet = baseContext.Set<T>();
        }

        public bool Delete(Expression<Func<T, bool>> match,bool isBatch=false)
        {
            //todo:批量删除，目前只删除一条内容
            if (isBatch)
            {
                return objectSet.Where(match).Delete() > 0;
            }
            else
            {
                return objectSet.Where(match).Delete(x => x.BatchSize = 1) > 0;
            }
            
        }

        public ICollection<T> Find(Expression<Func<T, bool>> match)
        {
            return objectSet.Where(match).ToList();
        }

        public T Find(object id)
        {
            return objectSet.Find(id);
        }

        public T FindSingle(Expression<Func<T, bool>> match)
        {
            return objectSet.FirstOrDefault(match);
        }

        public IList<T> GetAll(Expression<Func<T, bool>> where)
        {
            return objectSet.Where(where).ToList();
        }

        public IQueryable<T> GetQueryable()
        {
            return objectSet;
        }


        public bool Insert(T t)
        {
            objectSet.Add(t);
            return baseContext.SaveChanges() > 0;
        }

        public bool Update(Expression<Func<T, bool>> match, Expression<Func<T, T>> t)
        {
            return objectSet.Where(match).Update(t)>0;
        }
    }
}
